var JQUERY_DATA_NAME = 'text-edit';

function TextEditComponent($elm, options) {
    this.$elm = $elm;
    this.options = options;
    this.init();
}

TextEditComponent.prototype = {
    constructor: TextEditComponent,
    init: function() {
        let self = this;
        let $input = this.$elm.find("input");
        let oldValue = $input.val();

        let $ok = $('<i class="icon icon-inlineOk"></i>');
        let $cancel = $('<i class="icon icon-inlineCanel"></i>');

        this.$elm.on("click", ".icon-inlineOk", function(event) {
            let $this = $(this);
            $.myAjax({
                url: "device/updateAliasName.do",
                data: {
                    sn: self.options.sn,
                    aliasName: $input.val()
                },
                success: function(res) {
                    oldValue = $input.val();
                    $input.attr("readonly", true);
                    $this.remove();
                    $cancel.remove();
                    self.$elm.append($(`<i class="icon icon-inlineEdit"></i>`));
                }
            });
        });

        this.$elm.on("click", ".icon-inlineCanel", function() {
            $input.attr("readonly", true).val(oldValue);
            $(this).remove();
            $ok.remove();
            self.$elm.append($(`<i class="icon icon-inlineEdit"></i>`));
        });

        this.$elm.on("click", ".icon-inlineEdit", function() {
            $(this).remove();
            $input.attr("readonly", false).focus();
            self.$elm.append($ok).append($cancel);
        });

    }
}

$.fn.textEdit = function(options, value) {
    let $ele = this.each(function(i, item) {
        var $item = $(item);
        var component = $(item).data(JQUERY_DATA_NAME);
        if (!component) {
            component = new TextEditComponent($item, options);
        }
        if (typeof option === 'string') {
            component[options](value);
        } else {

        }
    });
    return $ele;
}

$.fn.textEdit.defaults = {

}
